const express = require("express");
const mongoose = require("mongoose");
const moment = require("moment");
const app = express();
async function connect(){
	if(mongoose.connection.readyState === 1) return Promise.resolve();
	return mongoose.connect("mongodb://127.0.0.1:27017/weibo",{
		serverSelectionTimeoutMS:10000
	})
}
function createModel(){
	// 生成schema
	const schema = new mongoose.Schema({
		context:{
			type:String,
			unique:true,
			required:true
		},
		addTime:{
			type:String,
			required:true
		},
		topNum:{
			type:Number,
			default:0
		},
		downNum:{
			type:Number,
			default:0
		}
	});
	// 生成model
	const model = mongoose.model("contentList",schema,"contentList");
	return model;
}
app.post("/weibo",async (req,res)=>{
	const {context} = req.body;
	// 连接
	await connect();
	const model = createModel();
	// 操作数据
	model({
		context,
		addTime:moment().format("YYYY-MM-DD hh:mm:ss")
	}).save().then(value=>{
		res.json({
			ok:1,
			msg:"添加成功"
		})
	}).catch(err=>{
		res.json({
			ok:-1,
			msg:"添加失败"
		})
	})
	
	
})
app.listen(8090,()=>{
	console.log("success");
})